from flask import request, abort, send_from_directory
from flask_login import current_user
import os
from script.api.general_code import INPUT_ERROR


def get_form_need(*get_keys):
    state = True
    keys = request.values.keys()
    values = []
    for key in get_keys:
        if key in keys:
            values.append(request.values.get(key))
        else:
            state = False
            values.append(None)
    values.insert(0, state)
    if not state:
        abort(403, INPUT_ERROR)
    return tuple(values)


def has_form_and_get(key, default_value=None):
    state = key in request.values.keys()
    if state:
        value = request.values.get(key)
    else:
        value = default_value
    return state, value


def in_directory(directory, file):
    directory = os.path.join(os.path.realpath(directory), '')
    file = os.path.realpath(file)
    return os.path.commonprefix([file, directory]) == directory


def check_and_send_file(directory, split_file):
    file_path = os.path.join(directory, split_file)
    if in_directory(directory, file_path):
        return send_from_directory(directory, split_file)
    else:
        abort(404)


def check_category_safe(category_id):
    category_id = int(category_id)
    user_all_categories = current_user.categories
    category_id_list = [c.id for c in user_all_categories]
    return category_id in category_id_list
